package com.ding.config;

import com.ding.pojo.Authority;
import com.ding.pojo.User;
import com.mysql.cj.jdbc.MysqlConnectionPoolDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class HibernateConfg {


    /*
    创建数据源
     */
    @Bean
    public DataSource dataSource() {

        MysqlConnectionPoolDataSource dataSource=new MysqlConnectionPoolDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC");
        dataSource.setUser("root");
        dataSource.setPassword("ding4311");
        return dataSource;
    }
    /*
        创建Hibernate会话工厂
     */
    @Bean
    public LocalSessionFactoryBean sessionFactoryBean(DataSource dataSource) {

        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setAnnotatedClasses(User.class, Authority.class);
        Properties properties = new Properties();

        properties.put("dialect", "org.hibernate.dialect.MySQL55Dialect");
        properties.put("hibernate.hbm2ddl.auto", "update");

        factoryBean.setHibernateProperties(properties);
        return factoryBean;
    }

    /*
            创建Hibernate事务管理器
     */
    @Bean
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        return new HibernateTransactionManager(sessionFactory);

    }


}
